//
//  CYLTVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/21.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYLTVC.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYHttpTool.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "UIImageView+WebCache.h"
#import "GCD.h"
#import "MBProgressHUD+LE.h"
#import "CYJsonInfo.h"

@interface CYLTVC ()

@property(nonatomic, strong) GCDTimer *GCDTimer;
@property (weak, nonatomic) IBOutlet UITextField *dealCodeTF;
@property (weak, nonatomic) IBOutlet UIButton *getdealcodeBtn;
@property (weak, nonatomic) IBOutlet UIImageView *dealcodeimageView;
@property (weak, nonatomic) IBOutlet UIButton *imagedealcodeyanzhengBtn;
@property (weak, nonatomic) IBOutlet UITextField *imagedealcodeTF;
@property (weak, nonatomic) IBOutlet UIButton *imagedealcodechangeBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (nonatomic, strong) NSString *mnoCertification;

@property (weak, nonatomic) IBOutlet UILabel *tishiLab;
@property (weak, nonatomic) IBOutlet UILabel *wenxintishiLab;


@end

@implementation CYLTVC

- (void)viewDidLoad {
    [super viewDidLoad];
     self.title = @"中国联通授权";

     CYUser *user = [CYLoginHttpTool userData].user;
     _tishiLab.text = [NSString stringWithFormat:@"手机号码（请使用%@名下的号码进行认证）",user.name];
     _wenxintishiLab.text = [NSString stringWithFormat:@"1.请授权本人（%@）实名认证手机号（使用满3个月）。",user.name];
     
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(submitclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"确定" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;
     
    // Do any additional setup after loading the view from its nib.
}

-(void)loadimagestatues{
     if (_phoneTF.text.length > 0 ) {
          NSDate *date = [NSDate date];
          NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
          //查询是否需要图形验证码
          [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/CheckNeedVerify" params:@{@"callback":@"jQuery172012197672072217403_1465203955306",@"userName":_phoneTF.text,@"pwdType":@"02",@"_":timeSp} success:^(id json) {
               NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
               
               NSString *string =jsonstr;
               int i1 = 0 ;
               int i2 = 0 ;
               for (int i = 0; i<[string length]; i++) {
                    //截取字符串中的每一个字符
                    NSString *s = [string substringWithRange:NSMakeRange(i, 1)];
                    NSLog(@"string is %@",s);
                    if ([s isEqualToString:@"("]) {
                         //记录它的位子
                         CYLog(@"i=%d",i);
                         i1 = i;
                    }
                    if ([s isEqualToString:@")"]) {
                         CYLog(@"i = %d",i);
                         i2 = i;
                    }
               }
               
               NSString *str1 =  [string substringWithRange:NSMakeRange(i1+1, (i2-i1-1))];
               CYLog(@"str = %@",str1);
               
               NSData *jsonData = [str1 dataUsingEncoding:NSUTF8StringEncoding];
               NSError *err;
               NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:&err];
               NSString *results = [dic objectForKey:@"resultCode"];
               if ([results isEqualToString:@"false"]) {
                    
                    //不需要
                    _imagedealcodeTF.placeholder = @"本次无需图形验证码";
                    _imagedealcodeTF.enabled = NO;
                    _imagedealcodechangeBtn.hidden = YES;
                    _imagedealcodeyanzhengBtn.hidden = YES;
                    
                    
               }else{
                    //需要
                    _imagedealcodeyanzhengBtn.hidden = NO;
                    
                    [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/CreateImage" params:@{@"t":timeSp} success:^(id json) {
                         
                         NSData *data = [NSData dataWithData:json];
                         UIImage *image = [UIImage imageWithData:data];
                         [_dealcodeimageView setImage:image];
                         
                         
                         
                         
                    } failure:^(NSError *error) {
                         
                    }];
                    
               }
               
          } failure:^(NSError *error) {
               
          }];

     }
     
}

- (IBAction)getdealcodeClick:(id)sender {
     if (_phoneTF.text.length == 0) {
          CYAlertView(@"请输入手机号");
          return;
     }
     
     [self loadimagestatues];
     //发送联通验证码
     [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/SendMSG" params:@{@"callback":@"jQuery17208861453778363799_1460008703715",@"req_time":@"1460010676219",@"mobile":_phoneTF.text,@"_":@"1460010676220"} success:^(id json) {
          NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          NSString *string =jsonstr;
          int i1 = 0 ;
          int i2 = 0 ;
          for (int i = 0; i<[string length]; i++) {
               //截取字符串中的每一个字符
               NSString *s = [string substringWithRange:NSMakeRange(i, 1)];
               if ([s isEqualToString:@"("]) {
                    //记录它的位子
                    i1 = i;
               }
               if ([s isEqualToString:@")"]) {
                    i2 = i;
               }
          }
          CYLog(@"i1 = %d,i2 = %d",i1,i2);
          
          NSString *str1 =  [string substringWithRange:NSMakeRange(i1+1, (i2-i1-1))];
          CYLog(@"str = %@",str1);
          
          NSData *jsonData = [str1 dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
          NSString *resultdicstr = [dic objectForKey:@"resultCode"];
          if ([resultdicstr isEqualToString:@"0000"]) {
               CYAlertView(@"发送成功");
               [self countdown:sender];
               
          }else{
               CYAlertView(@"发送成功");
               [self countdown:sender];
          }
          
     } failure:^(NSError *error) {
          
     }];
}
/**
 *  倒计时
 */

- (void)countdown:(UIButton *)btn {
     self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
     
     CYWeakObject(weakself, self);
     __block int time = 119;
     [self.GCDTimer event:^{
          if (time < 1) {
               //设置界面的按钮显示 根据自己需求设置
               [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
               btn.userInteractionEnabled = YES;
               //            btn.backgroundColor = CYColor(79, 118, 245, 1);
               [weakself.GCDTimer destroy];
          } else {
               //        NSLog(@"time:%d", time);
               [btn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
               btn.userInteractionEnabled = NO;
               //            btn.backgroundColor = CYColor(211, 211, 211, 1);
          }
          time--;
     } timeInterval:NSEC_PER_SEC * 1];
     [self.GCDTimer start];
}


- (IBAction)changeimagedealcodeClick:(id)sender {
     
     NSDate *date = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/CreateImage" params:@{@"t":timeSp} success:^(id json) {
          
          NSData *data = [NSData dataWithData:json];
          UIImage *image = [UIImage imageWithData:data];
          [_dealcodeimageView setImage:image];
          
     } failure:^(NSError *error) {
          
     }];

     
     
}

- (IBAction)imagedealcodeyanzhengClick:(id)sender {
     
     [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/CtaIdyChk" params:@{@"callback":@"jQuery1720040931962822211565_1465709690470",@"verifyCode":_imagedealcodeTF.text,@"verifyType":@"1",@"_":@"1465718236291"} success:^(id json) {
          NSString *jsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          NSString *string =jsonstr;
          int i1 = 0 ;
          int i2 = 0 ;
          for (int i = 0; i<[string length]; i++) {
               //截取字符串中的每一个字符
               NSString *s = [string substringWithRange:NSMakeRange(i, 1)];
               NSLog(@"string is %@",s);
               if ([s isEqualToString:@"("]) {
                    //记录它的位子
                    CYLog(@"i=%d",i);
                    i1 = i;
               }
               if ([s isEqualToString:@")"]) {
                    CYLog(@"i = %d",i);
                    i2 = i;
               }
          }
          
          CYLog(@"i1 = %d,i2 = %d",i1,i2);
          NSString *str1 =  [string substringWithRange:NSMakeRange(i1+1, (i2-i1-1))];
          CYLog(@"str = %@",str1);
          
          NSData *jsonData = [str1 dataUsingEncoding:NSUTF8StringEncoding];
          NSError *err;
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
                   CYLog(@"dic = %@",dic);
          NSString *resultstr = [dic objectForKey:@"resultCode"];
          if ([resultstr isEqualToString:@"true"]) {
               CYAlertView(@"验证通过!");
               
               
          }else{
               CYAlertView(@"验证不通过!");
          }

     } failure:^(NSError *error) {
          
     }];
     
}

-(void)submitclick{
     CYUser *user = [CYLoginHttpTool userData].user;
     NSDate *date = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
     if (_phoneTF.text.length ==0 ) {
          CYAlertView(@"请输入手机号");
          return;
     }
     if (_dealCodeTF.text.length == 0) {
          CYAlertView(@"请输入验证码");
          return;
     }
     if (_imagedealcodeTF.text.length == 0) {
          _imagedealcodeTF.text = @"";
     }
     //登陆
     [MBProgressHUD showMessage:nil toView:self.view];
     [CYHttpTool get10010WithURL:@"https://uac.10010.com/portal/Service/MallLogin" params:@{@"callback":@"jQuery17208807432631022365_1465202024842",@"req_time":@"1465202045639",@"redirectURL":@"http://iservice.10010.com/e3/",@"userName":_phoneTF.text,@"password":_dealCodeTF.text,@"pwdType":@"02",@"productType":@"01",@"verifyCode":_imagedealcodeTF.text,@"redirectType":@"01",@"rememberMe":@"1",@"_":timeSp,@"uvc":@""} success:^(id json) {
          [MBProgressHUD hideHUDForView:self.view animated:YES];
          NSString *loginjsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
          
          NSString *loginstring =loginjsonstr;
          int i1 = 0 ;
          int i2 = 0 ;
          for (int i = 0; i<[loginstring length]; i++) {
               //截取字符串中的每一个字符
               NSString *s = [loginstring substringWithRange:NSMakeRange(i, 1)];
               NSLog(@"string is %@",s);
               if ([s isEqualToString:@"("]) {
                    //记录它的位子
                    CYLog(@"i=%d",i);
                    i1 = i;
               }
               if ([s isEqualToString:@")"]) {
                    CYLog(@"i = %d",i);
                    i2 = i;
               }
          }
          CYLog(@"i1 = %d,i2 = %d",i1,i2);
          
          NSString *loginstr =  [loginstring substringWithRange:NSMakeRange(i1+1, (i2-i1-1))];
          if (loginstr) {
               //验证通过
               [MBProgressHUD showMessage:nil toView:self.view];
               [CYHttpTool get10010WithURL:@"https://uac.10010.com/cust/userinfo/userInfoInit" params:nil success:^(id json) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    NSString *yanzhengjsonstr = [[NSString alloc] initWithData:json  encoding:NSUTF8StringEncoding];
                    if (yanzhengjsonstr) {
                         //执行查询数据
                         [MBProgressHUD showMessage:nil toView:self.view];

                         [CYHttpTool postWithURL:@"http://iservice.10010.com/e3/static/check/checklogin/" params:@{@"_":@"1464326909124"} success:^(id json) {
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              NSString *datajsonstr = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
                              CYLog(@"datajsonstr = %@",datajsonstr);
                              NSData *jsonData = [datajsonstr dataUsingEncoding:NSUTF8StringEncoding];
                              NSError *err;
                              NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                                  options:NSJSONReadingMutableContainers
                                                                                    error:&err];
                              CYLog(@"dic = %@",dic);
                              if (dic.count) {
                                   NSDictionary *userinfodic = [dic objectForKey:@"userInfo"];
                                   if (userinfodic.count) {
                                        NSString *custname = [userinfodic objectForKey:@"custName"];
                                        NSString *opendate = [userinfodic objectForKey:@"opendate"];
                                        if (custname) {
                                             _mnoCertification = @"1";
                                             
                                        }else{
                                             _mnoCertification = @"0";
                                        }
                                        
                                        NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
                                        [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
                                        [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
                                        NSDate *inputDate = [inputFormatter dateFromString:opendate];
                                        NSString *netDateStr = [NSString stringWithFormat:@"%ld", (long)[inputDate timeIntervalSince1970]];
                                        
                                        double aNumber = [timeSp doubleValue];
                                        //网龄时间
                                        double netnumber = [netDateStr doubleValue];
                                        int daycount = (aNumber-netnumber)/60/60/24/30;//月为单位
                                        CYLog(@"datcount = %d",daycount);
                                        NSString *mnoAge = [NSString stringWithFormat:@"%d",daycount];
                                        CYLog(@"mnoAge = %@",mnoAge);
                                        if (daycount&&_mnoCertification) {
                                             [MBProgressHUD showMessage:nil toView:self.view];
                                             //执行运营商数据保存
                                             [CYHttpTool postWithURL:[CYURL shared].saveMno params:@{@"userId":user.userId,@"token":user.token,@"mnoCertification":_mnoCertification,@"mnoAge":mnoAge,@"name":custname,@"phone":_phoneTF.text} success:^(id json) {
                                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                  CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
                                                  if (jsoninfo.isSuccess) {
                                                        CYAlertView(jsoninfo.message);
                                                       //发送通知认证成功
                                                        [MBProgressHUD hideHUDForView:self.view animated:YES];[[NSNotificationCenter defaultCenter] postNotificationName:@"CYYYSNotification" object:nil userInfo:nil];
                                                       [self.navigationController popViewControllerAnimated:YES];
                                                       
                                                  }else{
                                                       [MBProgressHUD showMessage:jsoninfo.message];
                                                       [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                  }
                                                  
                                             } failure:^(NSError *error) {
                                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                  
                                             }];
                                             
                                        }

                                        [MBProgressHUD hideHUDForView:self.view animated:YES];
         
                                   }else{
                                        CYAlertView(@"授权失败");
                                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                                   }
                                   
                                   
                              }else{
                                   CYAlertView(@"授权失败");
                                   [MBProgressHUD hideHUDForView:self.view animated:YES];
                              }
                              [MBProgressHUD hideHUDForView:self.view animated:YES];
                              
                              
                              
                         } failure:^(NSError *error) {
                              CYAlertView(@"授权失败");
                              [MBProgressHUD hideHUDForView:self.view animated:YES];

                         }];
                    }
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
               } failure:^(NSError *error) {
                    CYLog(@"error = %@",error);
                    CYAlertView(@"授权失败");
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
               }];

               [MBProgressHUD hideHUDForView:self.view animated:YES];
          }else{
               CYAlertView(@"授权失败");
               [MBProgressHUD hideHUDForView:self.view animated:YES];
          }

     } failure:^(NSError *error) {
          CYLog(@"error = %@",error);
          CYAlertView(@"授权失败");
          [MBProgressHUD hideHUDForView:self.view animated:YES];
          
     }];
     
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
